﻿#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    client = new QMqttClient(this);
    client->setHostname("m6bn356.mqtt.iot.gz.baidubce.com");
    client->setPort(1883);
    client->setUsername("m6bn356/user");
    client->setPassword("zgf70f36dsf7erv6");
    client->setClientId("user");
    connect(client, SIGNAL(connected()), this, SLOT(on_connected()));
    client->connectToHost();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_connected()
{
    qDebug() << "Baidu IoT Hub is connected";
}

void Widget::on_pushButton_toggled(bool checked)
{
    if (!checked)
    {
        qDebug() << "关灯";
        client->publish(QString("$baidu/iot/shadow/test_esp8266/update"),
                        QByteArray("{\"requestId\":\"1234\",\"desired\":{\"light\":false}}"), 1);
        ui->pushButton->setText("开灯");
    }
    else
    {
        qDebug() << "开灯";
        client->publish(QString("$baidu/iot/shadow/test_esp8266/update"),
                        QByteArray("{\"requestId\":\"4321\",\"desired\":{\"light\":true}}"), 1);
        ui->pushButton->setText("关灯");
    }
}
